
package com.hlkj.pay.controller.ad;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.framework.common.util.date.LocalDateTimeUtils;
import com.hlkj.pay.app.ad.IAdAppService;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.dto.ad.query.AdInfoQueryDto;
import com.hlkj.pay.dto.ad.query.AdStatisticsQueryDto;
import com.hlkj.pay.infrastructure.model.ad.AdInfoConfigDO;
import com.hlkj.pay.infrastructure.model.ad.AdInfoDO;
import com.hlkj.pay.infrastructure.model.ad.AdMediaDO;
import com.hlkj.pay.infrastructure.model.ad.AdStatisticsDO;
import com.hlkj.pay.service.ad.IAdInfoService;
import com.hlkj.pay.service.ad.IAdMediaService;
import com.hlkj.pay.service.ad.IAdStatisticsService;
import com.hlkj.pay.vo.ad.req.*;
import com.hlkj.pay.vo.ad.resp.AdInfoConfigResp;
import com.hlkj.pay.vo.ad.resp.AdInfoResp;
import com.hlkj.pay.vo.ad.resp.AdInfoStatisticsResp;
import com.hlkj.pay.vo.common.req.DeleteIdReq;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;

/**
 * @author HlpayTeam
 * @date 2024/10/22 18:23
 */
@Tag(name = "广告信息管理")
@RestController
@RequestMapping("/v1/ad/info")
@RequiredArgsConstructor
@Slf4j
public class AdController extends BaseController {

    private final IAdInfoService adService;

    private final IAdAppService adAppService;

    private final IAdMediaService adMediaService;

    private final IAdStatisticsService adStatisticsService;

    @Operation(summary = "列表查询")
    @GetMapping("/page")
    CommonResult<PageResult<AdInfoResp>> queryAdPage(@Validated AdInfoPageQueryReq adInfoPageQueryReq) {
        AdInfoQueryDto adInfoQueryDto = BeanUtil.copy(adInfoPageQueryReq, AdInfoQueryDto.class);
        adInfoQueryDto.setName(null);
        adInfoQueryDto.setLikeName(adInfoPageQueryReq.getName());
        if(adInfoPageQueryReq.getMediaType()!=null){
            adInfoQueryDto.setMediaId(adInfoPageQueryReq.getMediaType());
        }
        PageResult<AdInfoDO> page = adService.queryPage(adInfoQueryDto);
        List<AdInfoDO> list = page.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(page, Collections.emptyList());
        }
        Set<Long> mediaIds = list.stream().map(adInfoDO -> adInfoDO.getMediaId()).collect(Collectors.toSet());
        List<AdMediaDO> mediaList = adMediaService.queryList(mediaIds);
        Map<Long, AdMediaDO> mediaMap = mediaList.stream().collect(Collectors.toMap(media -> media.getId(), Function.identity()));
        List<AdInfoResp> adInfoResps = cn.hutool.core.bean.BeanUtil.copyToList(list, AdInfoResp.class);
        adInfoResps.stream().forEach(adInfoResp -> {
            AdMediaDO adMediaDO = mediaMap.get(adInfoResp.getMediaId());
            if (adMediaDO != null) {
                adInfoResp.setMediaName(adMediaDO.getName());
            }
        });
        return buildPageResult(page, adInfoResps);
    }

    @Operation(summary = "信息详情")
    @GetMapping("/detail")
    CommonResult<AdInfoResp> detail(@RequestParam("id") Long id) {
        AdInfoDO adInfoDO = adService.queryById(id);
        if (adInfoDO == null) {
            return CommonResult.success(null);
        }
        AdInfoResp adInfoResp = BeanUtil.copy(adInfoDO, AdInfoResp.class);
        AdMediaDO adMediaDO = adMediaService.queryById(adInfoDO.getMediaId());
        if (adMediaDO != null) {
            adInfoResp.setMediaName(adMediaDO.getName());
        }
        return CommonResult.success(adInfoResp);
    }

    @Operation(summary = "新增广告")
    @PostMapping("")
    CommonResult<Void> saveAd(@Validated @RequestBody AdInfoReq adInfoReq) {
        return adAppService.saveAd(adInfoReq);
    }

    @Operation(summary = "更新广告")
    @PutMapping("")
    CommonResult<Void> updateAd(@Validated @RequestBody AdInfoReq payWayReq) {
        return adAppService.updateAd(payWayReq);
    }

    @Operation(summary = "删除广告")
    @DeleteMapping("")
    CommonResult<Void> delAd(@Validated @RequestBody DeleteIdReq deleteCodeReq) {
        return adAppService.delAd(deleteCodeReq.getId());
    }

    @Operation(summary = "更新状态")
    @PostMapping("/status")
    CommonResult<Void> updateAdStatus(@Validated @RequestBody UpdateStatusReq updateStatusReq) {
        return adAppService.updateAdStatus(updateStatusReq);
    }

    @Operation(summary = "获取广告配置")
    @GetMapping("/config")
    CommonResult<AdInfoConfigResp> adConfigDetail(@RequestParam("id") Long id) {
        AdInfoConfigDO adInfoConfigDO = adService.queryConfigByAdId(id);
        if (adInfoConfigDO == null) {
            return CommonResult.success(null);
        }
        return CommonResult.success(BeanUtil.copy(adInfoConfigDO, AdInfoConfigResp.class));
    }

    @Operation(summary = "保存广告配置")
    @PostMapping("/config")
    CommonResult<Void> updateAdConfig(@Validated @RequestBody AdInfoConfigReq adInfoConfigReq) {
        return adAppService.updateAdConfig(adInfoConfigReq);
    }

    @Operation(summary = "统计查询")
    @GetMapping("/statistics")
    CommonResult<PageResult<AdInfoStatisticsResp>> queryStatistics(AdStatisticsPageQueryReq adInfoConfigReq) {
        AdStatisticsQueryDto adInfoQueryDO = BeanUtil.copy(adInfoConfigReq, AdStatisticsQueryDto.class);
        if (StringUtils.hasText(adInfoConfigReq.getStartTime())) {
            try {
                LocalDateTime startTime = LocalDateTimeUtil.parse(adInfoConfigReq.getStartTime(), DatePattern.NORM_DATETIME_PATTERN);
                adInfoQueryDO.setStartQueryTime(LocalDateTimeUtils.datatimeToTimestamp(startTime));
            }
            catch (Exception e) {
                log.warn("queryStatistics cover start time error:{}", e.getMessage());
            }
        }
        if (StringUtils.hasText(adInfoConfigReq.getEndTime())) {
            try {
                LocalDateTime endTime = LocalDateTimeUtil.parse(adInfoConfigReq.getEndTime(), DatePattern.NORM_DATETIME_PATTERN);
                // + 1 day - 1 s
                LocalDateTime localDateTime = endTime.plusDays(1).plusSeconds(-1);
                adInfoQueryDO.setEndQueryTime(LocalDateTimeUtils.datatimeToTimestamp(localDateTime));
            }
            catch (Exception e) {
                log.warn("queryStatistics cover end time error:{}", e.getMessage());
            }
        }
        PageResult<AdStatisticsDO> page = adStatisticsService.queryPage(adInfoQueryDO);
        List<AdStatisticsDO> list = page.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(page, Collections.emptyList());
        }
        return buildPageResult(page, cn.hutool.core.bean.BeanUtil.copyToList(list, AdInfoStatisticsResp.class));
    }

}
